package nl.ViewerServer;

import nl.ViewerServer.ServerManager.Config;
import nl.ViewerServer.ServerManager.ServerManager;
import nl.ViewerServer.SessionManager.SessionManager;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Application {
   private static Logger      log = Logger.getLogger( Application.class );
   private static Application instance;
   public static Config       config;

   /**
    * @param args
    */
   public static void main( String[] args ) {
      // Watch the property file for the logging
      PropertyConfigurator.configureAndWatch( "log4j.properties", 15 );

      Application.getInstance();
   }

   public synchronized static Application getInstance() {
      if( instance == null ) {
         instance = new Application();
      }
      return instance;
   }

   private Application() {
      log.info( "ViewerServer initializing...." );

      try {
         config = Config.readConfig();
      }
      catch( Throwable t ) {
         log.error( "Could not read configuration (" + t + "), returning to default (a.k.a. development) configuration" );
         config = new Config();
      }

      // check for config sanity
      if( config.poolSize > config.paraviewThreadCount ) {
         log.fatal( "It is not allowed to have more workers in the pool than ParaView threads available" );
         return;
      }

      if( config.maxParaviewThreadCountPerWorker > config.paraviewThreadCount ) {
         log.warn( "Maximum thread count per worker is set higher than total maximum thread count" );
      }

      // start the managers
      ServerManager serv = ServerManager.getInstance();
      if( serv == null ) {
         log.info( "ServerManager could not be started, abort" );
         return;
      }

      SessionManager sess = SessionManager.getInstance();
      if( sess == null ) {
         log.info( "SessionManager could not be started, abort" );
         return;
      }
   }

   public void shutdown() {
      // shutdown all components
      SessionManager.getInstance().shutdown();

      ServerManager.getInstance().shutdown();

   }
}
